/*********************
 * 自定义工具方法
 * author : 丁涛
 * verson : 1.0
 */

import Vuex from '../../store/index.js'
import Config from '../../config.js'
import Router from './router.js'
import Api from './api.js'

let defFun = {
	//判断是否为空对象
	isNullObj:function(data){
		var arr = Object.keys(data);
		return arr.length == 0;
	},
	//判断是否存在数组中
	isInAarry: function(arr, obj) {
		let i = arr.length;
		while (i--) {
			if (arr[i] == obj) {
				return true;
			}
		}
		return false;
	},
	//判断内容是否为空(排除0)
	isNull: function(obj, type, msg) {
		type = type || 0;
		msg = msg || '暂无内容';
		if ((obj == '' || obj == null || obj == 'null' || obj == 'undefined') && obj !== 0) return type == 0 ? false : msg;
		if (typeof(obj) == 'undefined') return type == 0 ? false : msg;
		if (typeof(obj) == 'object' && (obj.length == 0 || JSON.stringify(obj) == '{}')) return type == 0 ? false : msg;
		return obj;
	},
	/**
	 * 手机号码合法性验证
	 * @author liuwenjn
	 **/
	phoneVerfication: function(id) {
		let reg =
			/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$|14[0-9]{1}[0-9]{8}$|16[0-9]{1}[0-9]{8}$|19[0-9]{1}[0-9]{8}/;
		if (!reg.test(id)) {
			return false;
		}
		return true;
	},
	// 隐藏部分类型
	plusXing: function(str, length, opt) {
		opt = opt || {};
		length = length || 4;
		let mask = opt.mask ? opt.mask : '*';
		var replacement = '';
		for (var i = 0; i < length; i++) {
			replacement += mask;
		}
		if(opt.phone){
			//隐藏手机
			var reg = /^(\d{3})\d{4}(\d{4})$/
			return str.replace(reg, '$1****$2')
		}else if (opt.email) {
			//隐藏邮箱
			if (String (str).indexOf ('@') > 0) {
				let newEmail, _str = str.split('@'), _s = '';
				if (_str[0].length > 4) {
					_s = str[0].substr (0, 4);
					for (let i = 0; i < _str[0].length - 4; i++) {
						_s += '*';
					}
				} else {
					_s = _str[0].substr (0, 1);
					for (let i = 0; i < _str[0].length - 1; i++) {
						_s += '*';
					}
				}
				newEmail = _s + '@' + _str[1];
				return newEmail;
			} else {
				return str;
			}
		} else if (opt.fromBegin) {
			//隐藏头部N个字
			var regexp = new RegExp('.{1,' + length + '}');
			return str.replace(regexp, replacement);
		} else if (opt.fromEnd){
			//隐藏尾部N个字
			var regexp = new RegExp('.{' + (str.length - length) + ',' + str.length + '}');
			return str.substring(0, (str.length - length)) + str.replace(regexp, replacement);
		}else {
			if(str.length < 5)opt.endLen = 0;
			var len = str.length - opt.frontLen - opt.endLen;
			var xing = '';
			for (var i=0;i<len;i++) {
				xing+='*';
			}
			return str.substring(0,opt.frontLen)+xing+str.substring(str.length-opt.endLen);
		}
	},
	// obj转url参数
	encodeSearchParams: function(param, key, encode) {
		if (!param) return '';
		var paramStr = '';
		var t = typeof(param);
		if (t == 'string' || t == 'number' || t == 'boolean') {
			paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
		} else {
			for (var i in param) {
				var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
				paramStr += defFun.encodeSearchParams(param[i], k, encode)
			}
		}
		return paramStr;
	},
	sortData:function(_data){
	  if('object' !== typeof _data) return {};
	
	  let _keys = Object.keys(_data).sort(), 
	    _newArr = {},
	    _str = "";
	
	  _keys.forEach(function(key, i){
	    _newArr[key] = _data[key]; 
	
	    if(i == 0){
	      _str = key+'='+_data[key];
	    }else{
	      _str += '&'+key+'='+_data[key];
	    }
	  });
	
	  return {
	    data: _newArr,
	    param: _str
	  };
	},
	
	//判断是否为数字
	isRealNum: function(val) {
		if (val === "" || val == null) {
			return false;
		}
		if (!isNaN(val)) {
			return true;
		} else {
			return false;
		}
	},
	//数组反序排列
	arrReverse: function(data) {
		let _list = [];
		for (var i = data.length - 1; i >= 0; i--) {
			_list.push(data[i]);
		}
		return _list;
	},
	//只能输入数字并保留2位小数点
	clearNoNum:function(e,len) {
		var obj = e.srcElement || e.target;
		if(String(obj.value).indexOf(".")>-1){
			obj.value = obj.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符  
			obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的  
			obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$","."); 
			obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数  
			if(obj.value.indexOf(".")< 0 && obj.value !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额 
				obj.value= parseFloat(obj.value); 
			}
		}
		return obj.value;
	},
	//关键字标红
	brightenKeyword(val, keyword) {
		val = val + '';
		if (val.indexOf(keyword) !== -1 && keyword !== '') {
			return val.replace(keyword, '<label style="color:#E61D23">' + keyword + '</label>');
		} else {
			return val
		}
	},
};

/**
 * 时间相关方法
 */
let dateFun = {
	pad: function(num, n) {
		var len = num.toString().length;
		while (len < n) {
			num = "0" + num;
			len++;
		}
		return num;
	},
	// 日期对比
	compareDate: function(s1, s2) {
		return ((new Date(s1.replace(/-/g, "\/"))) > (new Date(s2.replace(/-/g, "\/"))));
	},
	//获得当前时间
	getNowFormatDate: function() {
		var date = new Date();
		var seperator1 = "-";
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if (strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		var currentdate = year + seperator1 + month + seperator1 + strDate;
		return currentdate;
	},
	//获得当前是几号
	getNowDateDay: function() {
		var date = new Date();
		var strDate = date.getDate();
		
		if (strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		return strDate; 
	},
	// 格式化时间(YYYY-MM-DD H:m)
	getFormatDate: function(date, type) {
		var _datetime;
		if (/^[0-9]+$/.test(date)) {
			_datetime = parseInt(date);
		} else {
			_datetime = date;
		}
		var datetime = new Date(_datetime);
		var year = datetime.getFullYear();
		var month = datetime.getMonth() + 1; //js从0开始取 
		var date = datetime.getDate();
		var hour = datetime.getHours();
		var minutes = datetime.getMinutes();
		var second = datetime.getSeconds();
		if (month < 10) month = "0" + month;
		if (date < 10) date = "0" + date;
		if (type == 1) {
			return year + "-" + month + "-" + date + ' ' + dateFun.pad(hour, 2) + ':' + dateFun.pad(minutes, 2) + ':' +
				dateFun.pad(second, 2);
		} else {
			return year + "-" + month + "-" + date;
		}
	},
	// 计算年龄
	countAge: function(datetime) {
		var r = datetime.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
		if (r == null) return false;
		var d = new Date(r[1], r[3] - 1, r[4]);
		if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
			var Y = new Date().getFullYear();
			return Y - r[1];
		}
	},
	// 获得时间戳
	getTime: function() {
		return new Date().getTime();
	},
	setFormat: function(x) {
		if (x < 10) {
			x = "0" + x;
		}
		return x;
	},
	//获取当前时间（Y-m-d h:i:s）
	getNowtime: function() {
		var date = new Date(); //日期对象
		var now = "";
		now = date.getFullYear() + "-"; //读英文就行了
		now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; //取月的时候取的是当前月-1如果想取当前月+1就可以了
		now = now + dateFun.setFormat(date.getDate()) + " ";
		now = now + dateFun.setFormat(date.getHours()) + ":";
		now = now + dateFun.setFormat(date.getMinutes()) + ":";
		now = now + dateFun.setFormat(date.getSeconds()) + "";
		return now;
	},
	//获取当前日期（Y-m-d）
	getNowDate: function() {
		var date = new Date(); //日期对象
		var now = "";
		now = date.getFullYear() + "-"; //读英文就行了
		now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; //取月的时候取的是当前月-1如果想取当前月+1就可以了
		now = now + dateFun.setFormat(date.getDate());
		return now;
	},
	//获取从现在到 beforetime 分钟前的时间
	beforeNowtimeByMinu: function(beforetime) {
		var date = new Date(); //日期对象
		date.setMinutes(date.getMinutes() - beforetime);
		var now = "";
		now = date.getFullYear() + "-"; //读英文就行了
		now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; //取月的时候取的是当前月-1如果想取当前月+1就可以了
		now = now + dateFun.setFormat(date.getDate()) + " ";
		now = now + dateFun.setFormat(date.getHours()) + ":";
		now = now + dateFun.setFormat(date.getMinutes()) + ":";
		now = now + dateFun.setFormat(date.getSeconds()) + "";
		return now;
	},
	//计算时间(13位时间戳)
	getDateFromNowBy13: function(timestamp,type) {
		var prmdate = new Date(parseInt(timestamp));
		var nowDate = new Date();
		var nTime = new Date(parseInt(timestamp));
		var nYear = nTime.getFullYear();
		var nMonth = nTime.getMonth() + 1;
		var nDate = nTime.getDate();
		var nHour = nTime.getHours();
		var nMinute = nTime.getMinutes();
		var second = nTime.getSeconds();
		if(type == 1){
			var _date = nYear + '-' + dateFun.pad(nMonth, 2) + '-' + dateFun.pad(nDate, 2) + ' ' +  dateFun.pad(nHour, 2) + ':' + dateFun.pad(nMinute, 2) + ':' +
					dateFun.pad(second, 2);
		}else{
			var _date = nYear + '-' + dateFun.pad(nMonth, 2) + '-' + dateFun.pad(nDate, 2);
		}
		
		return _date;
	},
	/**
	 * 计算多少时间前
	 * timestamp 时间戳/日期
	 * type 类型，默认为时间戳，如果是日期传入date
	 */
	getShortTime: function(timestamp,type) {
		if(type == 'date'){
			var date = timestamp;
			date = date.substring(0,19);    
			date = date.replace(/-/g,'/'); 
			timestamp = new Date(date).getTime();
		}
		var nowtime = (new Date).getTime(); /*当前时间戳*/
		/*转换时间，计算差值*/
		var secondNum = parseInt((nowtime - timestamp) / 1000); //计算时间戳差值 
		if (secondNum < 0) secondNum = 1;
		if (secondNum >= 0 && secondNum < 60) {
			if (secondNum >= 0 && secondNum < 5) {
				return '刚刚';
			} else {
				return '1分钟前';
			}
		} else if (secondNum >= 60 && secondNum < 3600) {
			var nTime = parseInt(secondNum / 60);
			return nTime + '分钟前';
		} else if (secondNum >= 3600 && secondNum < 3600 * 24) {
			var nTime = parseInt(secondNum / 3600);
			return nTime + '小时前';
		} else {
			var nTime = new Date(parseInt(timestamp));
			var nYear = nTime.getFullYear();
			var nMonth = nTime.getMonth() + 1;
			var nDate = nTime.getDate();
			var nHour = nTime.getHours();
			var nMinute = nTime.getMinutes();
			var year = (new Date).getFullYear();
			if (year == nYear) {
				return dateFun.pad(nMonth, 2) + '-' + dateFun.pad(nDate, 2) + ' ' + dateFun.pad(nHour, 2) + ':' + dateFun.pad(
					nMinute, 2);
			} else {
				return nYear + '-' + dateFun.pad(nMonth, 2) + '-' + dateFun.pad(nDate, 2) + ' ' + dateFun.pad(nHour, 2) + ':' +
					dateFun.pad(nMinute, 2);
			}
		}
	},
	//计算时间戳距离当前时间多少分钟
	getShortTime2: function(timestamp) {
		var nowtime = (new Date).getTime(); /*当前时间戳*/
		/*转换时间，计算差值*/
		var secondNum = parseInt((nowtime - timestamp) / 1000); //计算时间戳差值 
		var nTime = parseInt(secondNum / 60);
		return nTime;
	},
	//判断时间戳是否为今天
	isToday: function(str) {
		if (!str) return false;
		if (new Date(str).toDateString() === new Date().toDateString()) {
			//今天
			return true;
		} else if (new Date(str) < new Date()) {
			//之前
			return false;
		}
		return false;
	},
	//计算剩余使用天数
	getdateDiff: function(endTime) {
		var day = 24 * 60 * 60 * 1000;
		var date = new Date(); /*当前时间*/
		var now = "";
		now = date.getFullYear() + "-";
		now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
		now = now + dateFun.setFormat(date.getDate()) + " ";
		try {
			var dateArr = endTime.split("-");
			var checkDate = new Date();
			checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
			var checkTime = checkDate.getTime();
			var dateArr2 = now.split("-");
			var checkDate2 = new Date();
			checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
			var checkTime2 = checkDate2.getTime();
			var cha = (checkTime - checkTime2) / day;
			return parseInt(cha);
		} catch (e) {
			return false;
		}
	},
	//倒计时
	InitTime(endDate) {
		if(endDate){
			let isToday = dateFun.isToday(endDate);
			if(isToday){
				var day3 = new Date();
				day3.setTime(day3.getTime()+24*60*60*1000);
				endDate = dateFun.getFormatDate(day3);
			}
			var a = endDate;
			var dd, hh, mm, ss = null;
			let endDates = endDate.replace(/\-/g, '\/');
			let endTime = new Date(endDates);
			var time = (parseInt(endTime.getTime()) - new Date().getTime()) / 1000;
			if (isNaN(time) || time <= 0) {
				return '';
			} else {
				dd = Math.floor(time / 60 / 60 / 24);
				hh = Math.floor((time / 60 / 60) % 24);
				mm = Math.floor((time / 60) % 60);
				ss = Math.floor(time % 60);
				var str ='';
				if(dd >0){
					str = dd + "天" + hh + "时" + mm + "分" + ss+"秒";
				}else{
					str =  hh + "时" + mm + "分" + ss+"秒";
				}		
				return  str;		
			}
		}
	},
	//获得当前时间 2020-02
	getNowYearMo: function() {
		var date = new Date();
		var seperator1 = "-";
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		var currentdate = year + seperator1 + month;
		return currentdate;
	}
};

// 验证方法
const checkerFun = {
	error:'',
	check : function (data, rule){
		for(var i = 0; i < rule.length; i++){
			if (!rule[i].checkType){return true;}
			if (!rule[i].name) {return true;}
			if (!rule[i].errorMsg) {return true;}
			if (!data[rule[i].name]) {this.error = rule[i].errorMsg; return false;}
			switch (rule[i].checkType){
				case 'string':
					var reg = new RegExp('^.{' + rule[i].checkRule + '}$');
					if(!reg.test(data[rule[i].name])) {this.error = rule[i].errorMsg; return false;}
				break;
				case 'int':
					var reg = new RegExp('^(-[1-9]|[1-9])[0-9]{' + rule[i].checkRule + '}$');
					if(!reg.test(data[rule[i].name])) {this.error = rule[i].errorMsg; return false;}
					break;
				break;
				case 'between':
					if (!this.isNumber(data[rule[i].name])){
						this.error = rule[i].errorMsg;
						return false;
					}
					var minMax = rule[i].checkRule.split(',');
					minMax[0] = Number(minMax[0]);
					minMax[1] = Number(minMax[1]);
					if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
						this.error = rule[i].errorMsg;
						return false;
					}
				break;
				case 'betweenD':
					var reg = /^-?[1-9][0-9]?$/;
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
					var minMax = rule[i].checkRule.split(',');
					minMax[0] = Number(minMax[0]);
					minMax[1] = Number(minMax[1]);
					if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
						this.error = rule[i].errorMsg;
						return false;
					}
				break;
				case 'betweenF': 
					var reg = /^-?[0-9][0-9]?.+[0-9]+$/;
					if (!reg.test(data[rule[i].name])){this.error = rule[i].errorMsg; return false;}
					var minMax = rule[i].checkRule.split(',');
					minMax[0] = Number(minMax[0]);
					minMax[1] = Number(minMax[1]);
					if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
						this.error = rule[i].errorMsg;
						return false;
					}
				break;
				case 'same':
					if (data[rule[i].name] != rule[i].checkRule) { this.error = rule[i].errorMsg; return false;}
				break;
				case 'notsame':
					if (data[rule[i].name] == rule[i].checkRule) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'email':
					var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'phoneno':
					var reg = /^1[0-9]{10,10}$/;
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'zipcode':
					var reg = /^[0-9]{6}$/;
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'tellandphone':
					var reg = /^\d{7,11}$/;
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'reg':
					var reg = new RegExp(rule[i].checkRule);
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'in':
					if(rule[i].checkRule.indexOf(data[rule[i].name]) == -1){
						this.error = rule[i].errorMsg; return false;
					}
				break;
				case 'notnull':
					if(data[rule[i].name] == null || data[rule[i].name].length < 1){this.error = rule[i].errorMsg; return false;}
				break;
			}
		}
		return true;
	},
	isNumber : function (checkVal){
		checkVal = Number(checkVal);
		if(checkVal == NaN){return false;}
		return true;
	}
};



/********************************************** uniApp相关方法 **********************************************/

/**
 * 推送相关
 */
let pushFun = {
	toPage(data){
		if(typeof data == 'string'){
			data = JSON.parse(data);
		}
		if(data.onType == 'router'){
			webViewFun.default(data.onUrl,data.onData);
		}else if(data.onType == 'webview'){
			webViewFun.default('webview',{url:data.onUrl});
		}
	},
};

/**
 * 存储方法
 */
let localStorage = {
	set(key,val){uni.setStorage({key:key,data:val,success:(res)=>{return true},fail:()=>{return false}})},
	get(key){try{return uni.getStorageSync(key)}catch(e){return''}},
	remove(key){try{uni.removeStorageSync(key)}catch(e){}},
	clear(){uni.clearStorageSync()}
};


/**
 * 手机设备
 */

let deviceFun = {
	//判断号码是否加密
	 isCrypt :function(tell) {
		try {
			if(tell){
				let str = tell.replace(/ /, "+");
				let callTellPhone = CryptoFun.DeCrypt(str);
				return callTellPhone;
			}else{
				return "";
			}
		} catch(e) {
			return tell;
		}
	},
	//判断是否是数字还是号码
	isNumberPhone:function(callVal) {
		let TellPhone = '';
		let reg = /^[0-9]+.?[0-9]*$/;
		if(reg.test(callVal)) {
			return TellPhone = callVal;
		} else {
			return	TellPhone = deviceFun.isCrypt(callVal);
		}
	},
	// 拨打电话
	makePhoneCall: function(callVal) {
		let TellPhone = '';
		let reg = /^[0-9]+.?[0-9]*$/;
		TellPhone = callVal;
		uni.makePhoneCall({
			phoneNumber: TellPhone,
			success: function() {
				// 成功拨打电话
			},
			fail: function() {
				// tipsFun.toast.error('拨打失败');
			}
		});
	},
	// 扫描二维码
	scanQRCode: function(successCallback, errorCallback) {
		uni.scanCode({
			scanType: 'qrCode',
			success: function(res) {
				successCallback && successCallback(res.result);
			},
			fail: function(res) {
				tipsFun.toast.error('识别失败');
				errorCallback && errorCallback(res);
			}
		})
	},
	// 设置内容到剪切板
	setClipboard: function(data,successCallback, errorCallback) {
		if (data.length === 0) {
			tipsFun.toast.error('复制内容失败')
		} else {
			uni.setClipboardData({
				data: data,
				success: () => {
					successCallback && successCallback();
				},
				fail: () => {
					tipsFun.toast.error('储存数据失败');
					errorCallback && errorCallback();
				}
			});
		}
	},
	// 获得剪切板内容
	getClipboard: function(successCallback) {
		uni.getClipboardData({
			success: (res) => {
				return successCallback && successCallback(res.data);
			},
			fail: () => {
				tipsFun.toast.error('读取剪贴板失败')
			}
		});
	},
	//获取当前位置
	getCurrentPosition: function(callback) {
		try {
			let currentPosition = new Object();
			plus.geolocation.getCurrentPosition(function(position) {
				var codns = position.coords;
				currentPosition.address = position.address;
				currentPosition.addresses = position.addresses;
				currentPosition.timestamp = position.timestamp;
				currentPosition.latitude = codns.latitude;
				currentPosition.longitude = codns.longitude;
				Vuex.commit("setPosition",currentPosition);
			}, function(e) {
			}, {
				provider: 'baidu'
			});
		} catch (e) {
		}
	},
	//获取系统信息
	getSystemInfo:function(){
		uni.getSystemInfo({
			success: (res) => {
				// #ifndef H5
				let osType = res.platform == 'ios' ? 2 : 1;
				Vuex.commit("setState",{id:'osType',value:osType});
				
				Vuex.commit("setState",{id:'platform',value:res.platform});
				// #endif
				Vuex.commit("setState",{id:'brand',value:res.brand});
				Vuex.commit("setState",{id:'model',value:res.model});
				Vuex.commit("setState",{id:'windowHeight',value:res.windowHeight});
				Vuex.commit("setState",{id:'windowWidth',value:res.windowWidth});
			},
			fail: () => {
			}
		});
	}
};

/**
 * 页面跳转
 * url 页面地址或者自定义路由名称（参考router.js）
 */
let webViewFun = {
	/**
	 * 跳转新页面
	 * @param {String} url 路由地址/自定义路由名称
	 * @param {Object} objData
	 * @param {Boolean} type 是否使用自定义路由
	 * @param {Object} opt 其他参数，animationType 打开页面动画 animationDuration 动画时间 
	 */
	default: function(url, objData,type,opt) {
		try{
			type = type || true;
			opt = opt || {};
			if(type){
				let _url = Router.beforeEach(url);
				if(_url){
					let info = {};
					info.url = _url + '?' + defFun.encodeSearchParams(objData);
					if(opt.animationType){
						info.animationType = opt.animationType;
						info.animationDuration = opt.animationDuration || "200";
					}
					uni.navigateTo(info)
				}
			}else{
				uni.navigateTo({
					url: url + '?' + defFun.encodeSearchParams(objData)
				})
			}
		}catch(e){
			//TODO handle the exception
		}
	},
	/**
	 * 关闭当前页面，跳转到指定页面
	 * @param {String} url 路由地址/自定义路由名称
	 * @param {Object} objData
	 * @param {Boolean} type 是否使用自定义路由
	 * @param {Object} opt 其他参数，animationType 打开页面动画 animationDuration 动画时间 
	 */
	redirectTo: function(url, objData,type,opt) {
		type = type || true;
		opt = opt || {};
		if(type){
			let _url = Router.beforeEach(url);
			if(_url){
				let info = {};
				info.url = _url + '?' + defFun.encodeSearchParams(objData);
				if(opt.animationType){
					info.animationType = opt.animationType;
					info.animationDuration = opt.animationDuration || "200";
				}
				uni.redirectTo(info);
			}
		}else{
			uni.redirectTo({
				url: url + '?' + defFun.encodeSearchParams(objData)
			})
		}
	},
	// 关闭所有页面，打开指定页面
	reLaunch: function(url, objData,type) {
		type = type || true;
		if(type){
			let _url = Router.beforeEach(url);
			uni.reLaunch({
				url: _url + '?' + defFun.encodeSearchParams(objData)
			})
		}else{
			uni.reLaunch({
				url: url + '?' + defFun.encodeSearchParams(objData)
			})
		}
	},
	// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
	switchTab: function(url,type) {
		type = type || true;
		if(type){
			let _url = Router.beforeEach(url);
			uni.switchTab({
				url: _url
			})
		}else{
			uni.switchTab({
				url: url 
			})
		}
	},
	// 关闭当前页面，返回上一页面或多级页面
	back: function(delta) {
		uni.navigateBack({
			delta: delta || 1
		});
	}
};

/**
 * 分享方法
 * provider 分享供应商（weixin 微信，sinaweibo 新浪微博，qq QQ）
 * scene 微信分享的场景（WXSceneSession 分享到聊天界面，WXSenceTimeline 分享到朋友圈，WXSceneFavorite 分享到微信收藏）
 * type 分享内容类型（0 图文，1 纯文字，2 纯图片，3 音乐，4 视频，5 小程序）
 * title 分享标题
 * summary 分享摘要
 * href 跳转地址
 * imageUrl 分享图片地址
 * mediaUrl 音视频地址
 * miniProgram 分享小程序必要参数
 */
let shareFun = {
	// 分享图文
	async default (opt, successCallback, errorCallback) {
		// if (plus.os.name === 'iOS') {
		// 	//ios平台，则压缩图片 
		// 	opt.imageUrl = await shareFun.compress(opt.imageUrl);
		// }
		uni.share({
			provider: opt.provider,
			scene: opt.scene,
			type: opt.type || 0,
			href: opt.href,
			imageUrl: opt.imageUrl,
			title: opt.title,
			summary: opt.summary,
			success: function(res) {
				successCallback && successCallback(res);
			},
			fail: function(err) {
				tipsFun.toast.error('分享失败')
				errorCallback && errorCallback(err);
			},
			complete: function() {

			}
		});
	},
	// 分享纯文字
	text: function(opt, successCallback, errorCallback) {
		uni.share({
			provider: opt.provider,
			scene: opt.scene,
			type: 1,
			summary: opt.summary,
			success: function(res) {
				successCallback && successCallback(res);
			},
			fail: function(err) {
				tipsFun.toast.error('分享失败')
				errorCallback && errorCallback(err);
			},
			complete: function() {

			}
		});
	},
	// 分享纯图片
	img: function(opt, successCallback, errorCallback) {
		uni.share({
			provider: opt.provider,
			scene: opt.scene,
			type: 2,
			imageUrl: opt.imageUrl,
			success: function(res) {
				successCallback && successCallback(res);
			},
			fail: function(err) {
				tipsFun.toast.error('分享失败')
				errorCallback && errorCallback(err);
			},
			complete: function() {

			}
		});
	},
	//分享到小程序
	applet: function(opt, successCallback, errorCallback) {
		uni.share({
			provider: opt.provider,
			type: 5,
			imageUrl: opt.imageUrl,
			title: opt.title,
			miniProgram: opt.miniProgram,
			success: function(res) {
				successCallback && successCallback(res);
			},
			fail: function(err) {
				tipsFun.toast.error('分享失败')
				errorCallback && errorCallback(err);
			},
			complete: function() {

			}
		});
	},
	//压缩图片 图文分享要求分享图片大小不能超过20Kb
	compress: function(image) {
		var img = image || "/_www/logo.png";
		return new Promise((res) => {
			var localPath = plus.io.convertAbsoluteFileSystem(img.replace('file://', ''));
			// 压缩size
			plus.io.resolveLocalFileSystemURL(localPath, (entry) => {
				entry.file((file) => { // 可通过entry对象操作图片 
					if (file.size > 20480) { // 压缩后size 大于20Kb
						plus.zip.compressImage({
							src: img,
							dst: img.replace('.jpg', '2222.jpg').replace('.JPG', '2222.JPG'),
							width: '10%',
							height: '10%',
							quality: 1,
							overwrite: true
						}, (event) => {
							let newImg = img.replace('.jpg', '2222.jpg').replace('.JPG', '2222.JPG');
							res(newImg);
						}, function(error) {
							uni.showModal({
								content: "分享图片太大,需要请重新选择图片!",
								showCancel: false
							})
						});
					}
				});
			}, (e) => {
				uni.showModal({
					content: "分享图片太大,需要请重新选择图片!",
					showCancel: false
				})
			});
		})
	}
};


/**
 * 提示方法
 */
let tipsFun = {
	toast: {
		// 默认提示
		default: function(title) {
			uni.showToast({
				title: title,
				icon: 'none'
			});
		},
		// 成功提示
		success: function(title) {
			uni.showToast({
				title: title,
				icon: 'success'
			});
		},
		// 失败提示
		error: function(title) {
			uni.showToast({
				title: title,
				icon: 'none',
			});
		},
		// 加载中
		loading: function(title, mask) {
			var _title = title || Config.LOADINGWORDS;
			uni.showToast({
				title: _title,
				mask: mask || true,
				icon: 'loading'
			});
		},
		// 关闭toast
		close: function() {
			uni.hideToast();
		}
	},
	/**
	 * 弹框提示
	 * content 提示内容
	 * title 提示标题，默认从配置文件中读取
	 * opt 相关配置
	 */
	model: function(content, successCallback, errorCallback, opt) {
		var _title = Config.TIPSTITLE;
		var _showCancel = true, //是否显示取消按钮
			_cancelText = '取消', //取消按钮的文字，最多 4 个字符
			_cancelColor = '#000000', //取消按钮的文字颜色
			_confirmText = '确定', //确定按钮的文字，最多 4 个字符
			_confirmColor = '#3CC51F'; //确定按钮的文字颜色
		if (opt) {
			_title = opt.title || _title;
			_showCancel = opt.showCancel || _showCancel;
			_cancelText = opt.cancelText || _cancelText;
			_cancelColor = opt.cancelColor || _cancelColor;
			_confirmText = opt.confirmText || _confirmText;
			_confirmColor = opt.confirmColor || _confirmColor;
		}
		uni.showModal({
			title: _title,
			content: content,
			showCancel: _showCancel,
			cancelText: _cancelText,
			cancelColor: _cancelColor,
			confirmText: _confirmText,
			confirmColor: _confirmColor,
			success: function(res) {
				if (res.confirm) {
					// 点击确定
					successCallback && successCallback(res);
				} else if (res.cancel) {
					// 点击取消
					errorCallback && errorCallback(res);
				}
			}
		});
	},
	/**
	 * 下方弹出菜单
	 * itemList 按钮的文字数组，数组长度最大为6个
	 * opt 其他设置
	 */
	actionSheet: function(itemList, successCallback, errorCallback, opt) {
		var _itemColor = '#000000';
		if (opt) {
			_itemColor = opt.itemColor || _itemColor;
		}
		uni.showActionSheet({
			itemList: itemList,
			itemColor: _itemColor,
			success: function(res) {
				successCallback && successCallback(res.tapIndex + 1)
			},
			fail: function(res) {
				// 失败
				errorCallback && errorCallback(res)
			}
		});
	},
};

/**
 * 媒体方法
 */
let mediaFun = {
	// 打开相册或拍照
	getImages: function(count, successCallback, errorCallback) {
		uni.chooseImage({
			count: count || 1,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'],
			success: function(res) {
				successCallback && successCallback(res.tempFilePaths);
			},
			fail: function(err) {
				errorCallback && errorCallback(err);
			}
		});
	},
	// 打开相册
	getImagesByAlbum: function(count, successCallback, errorCallback) {
		uni.chooseImage({
			count: count || 1,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'],
			success: function(res) {
				successCallback && successCallback(res.tempFilePaths)
			},
			fail: function(err) {
				errorCallback && errorCallback(err);
			}
		});
	},
	// 打开拍照
	getImagesByCamera: function(count, successCallback, errorCallback) {
		uni.chooseImage({
			count: count || 1,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['camera'],
			success: function(res) {
				successCallback && successCallback(res.tempFilePaths)
			},
			fail: function(err) {
				errorCallback && errorCallback(err);
			}
		});
	},
	// 图片预览
	previewImage:function(current,urls, opt,successCallback,errorCallback) {
		opt = opt || {};
		uni.previewImage({
			current: current||0,//当前显示图片的链接，不填则默认为 urls 的第一张
			urls: urls,//需要预览的图片链接列表,['1.png','2.png']
			indicator: opt.indicator||'number',//图片指示器样式，可取值： "default" - 底部圆点指示器； "number" - 顶部数字指示器； "none" - 不显示指示器。
			loop: opt.loop||false, //是否可循环预览，默认值为"false"
			longPressActions: {
				itemList: opt.itemList||['识别二维码', '保存图片'],
                success: function (res) {
					let imgIndex = res.index || 0;
					if(res.tapIndex == 0){
						//识别二维码
						let reqInfo = {};
						reqInfo.loading = 2;
						reqInfo.imgUrl = urls[imgIndex];
						Api.Default.discernCode(reqInfo,rst=>{
							successCallback && successCallback(res)
						},err=>{
							errorCallback && errorCallback(err);
						})
					}else if(res.tapIndex == 1){
						//保存图片到相册
						tipsFun.toast.loading("正在保存...");
						let img = urls[imgIndex];
						mediaFun.downloadFile(img,rtn=>{
							//下载文件
							console.log("下载成功");
							mediaFun.saveImageToPhotosAlbum(rtn.tempFilePath,image=>{
								tipsFun.toast.close();
								tipsFun.toast.default("保存成功！");
							},err=>{
								tipsFun.toast.close();
								tipsFun.toast.default("保存失败，原因："+err);
							});
						});
						
					}
                },
                fail: function (res) {
                    errorCallback && errorCallback(err);
                }    
            }
		});
	},
	/**
	 * 获取图片信息
	 * url 图片的路径，可以是相对路径，临时文件路径，存储文件路径，网络图片路径
	 */
	getImageInfo:function(url,successCallback,errorCallback){
		uni.getImageInfo({
            src: url,
            success: function (image) {
                successCallback && successCallback(image)
            },
			fail: function(){
				errorCallback && errorCallback(false);
			}
        });
	},
	/**
	 * 图片懒加载
	 * list 图片数组
	 * node 图片节点
	 */
	loadImage:function(list,node){
		uni.createSelectorQuery().selectAll(node).boundingClientRect((images) => {
			images.forEach((image, index) => {
				if (image.top <= Vuex.state.windowHeight) {
					if(list[image.dataset.index])list[image.dataset.index].showImage = true;
				}
			})
		}).exec()
	},
	/**
	 * 下载文件
	 */
	downloadFile:function(url,successCallback,errorCallback){
		uni.downloadFile({
			url: url,
			success: (res) => {
				successCallback && successCallback(res);
			},
			fail:(err)=>{
				console.log(err);
				errorCallback && errorCallback(err)
			}
		});
	},
	/**
	 * 将下载的文件保存到本地
	 */
	saveFile:function(url,successCallback,errorCallback){
		uni.saveFile({
			tempFilePath: url,
			success: (res) => {
				console.log(res);
				successCallback && successCallback(res.savedFilePath)
			},
			fail:(err)=>{
				console.log(err);
				errorCallback && errorCallback(err)
			}
		});
	},
	/**
	 * 将下载的文件保存到相册
	 */
	saveImageToPhotosAlbum:function(url,successCallback,errorCallback){
		uni.saveImageToPhotosAlbum({
			filePath: url,
			success: (res) => {
				successCallback&&successCallback(res);
			},
			fail:(err)=>{
				tipsFun.model(JSON.stringify(err),res=>{
					errorCallback&&errorCallback(err);
				})
				
			}
		});
	},
};

/**
 * 设置tabBar
 */
let tabBarFun = {
	/**
	 * 设置tabBar 某一项右上角文本角标
	 * index tabBar的哪一项，从左边算起，起始是0
	 * text 显示的文本，不超过 3 个半角字符
	 */
	setBadge(index, text) {
		try{
			uni.setTabBarBadge({
				index: index,
				text: text.toString()
			})
		}catch(e){
			//TODO handle the exception
		}
	},
	/**
	 * 移除 tabBar 某一项右上角的文本
	 * index tabBar的哪一项，从左边算起，起始是0
	 */
	removeBadge(index) {
		try{
			uni.removeTabBarBadge({
				index: index
			})
		}catch(e){
			//TODO handle the exception
		}
	},
	/**
	 * 显示 tabBar 某一项的右上角的红点
	 */
	showRedDot(index) {
		uni.showTabBarRedDot({
			index: index
		})
	},
	/**
	 * 隐藏 tabBar 某一项的右上角的红点
	 */
	hideRedDot(index) {
		uni.hideTabBarRedDot({
			index: index
		})
	}
};

/**
 * 接口请求方法
 */
let apiFun = {
	/**
	 * 通用请求服务器接口
	 * apiName 接口地址
	 * data 请求数据
	 * method 请求方式
	 * successCallback 请求成功回调方法
	 * errorCallback 请求失败回调方法
	 */
	getDataFromServer(apiName, datas, method, successCallback, errorCallback) {
		method = method||'POST';
		if (datas.loading != 1) tipsFun.toast.loading();
		let reqData = JSON.parse(JSON.stringify(datas));;
		delete reqData.loading;
		uni.request({
			url: Config.server + apiName,
			method: method,
			header: {
				'Content-Type': 'application/json',
			},
			data: reqData,
			success: (res) => {
				// 请求接口成功
				tipsFun.toast.close();
				if (res.data.code == Config.SUCCESSCODE || res.data.code == '0') {
					successCallback && successCallback(res.data);
				} else if (res.data.code == 403){
					//清空登录状态
					if (datas.loading != 1) tipsFun.toast.error(res.data.message||Config.ERRORMSG);
					Vuex.commit("logout");
					errorCallback && errorCallback(res.data);
				} else {
					console.log("**************************")
					console.log("失败，接口："+apiName)
					console.log("失败，参数："+JSON.stringify(datas))
					console.log("失败，返回值："+JSON.stringify(res))
					console.log("**************************")
					tipsFun.toast.error(res.data.message);
					if (datas.loading != 1) tipsFun.toast.error(res.data.message||Config.ERRORMSG);
					errorCallback && errorCallback(res.data);
				}
			},
			fail: (err) => {
				console.log("**************************")
				console.log("接口错误，接口："+apiName)
				console.log("接口错误，参数："+JSON.stringify(data))
				console.log("接口错误，返回值："+JSON.stringify(err))
				console.log("**************************")
				// 请求接口失败
				tipsFun.toast.close();
				errorCallback && errorCallback(err);
				if (data.loading != 1) tipsFun.toast.error(Config.ERRORMSG);
			},
			complete: () => {
				// 成功、失败都执行

			}
		})
	},
	/**
	 * 上传文件
	 * apiName 接口地址
	 * files 需要上传的文件，arrr类型
	 * data 请求数据
	 * method 请求方式
	 * successCallback 请求成功回调方法
	 * errorCallback 请求失败回调方法
	 */
	UploadFilesFromServer(apiName, files, data, successCallback, errorCallback) {
		if (data.loading != 1) tipsFun.toast.loading('正在上传...');
		let reqData = data;
		delete reqData.loading;
		reqData.sign = defFun.getSign(reqData);
		uni.uploadFile({
			url: Config.SERVERURL + apiName,
			files: files,
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'token': Vuex.state.user_token,
				'platform' : Vuex.state.platform,
				'deviceId' : Vuex.state.deviceId,
				'version' : Vuex.state.version,
			},
			formData: data,
			success: (res) => {
				if(typeof(res.data) == "string"){
					res.data = JSON.parse(res.data);
				}
				// 上传成功
				tipsFun.toast.close();
				if (res.data.code == Config.SUCCESSCODE) {
					successCallback && successCallback(res.data);
				} else {
					console.log("**************************")
					console.log("失败，接口："+apiName)
					console.log("失败，参数："+JSON.stringify(data))
					console.log("失败，返回值："+JSON.stringify(res))
					console.log("**************************")
					errorCallback && errorCallback(res.data);
					if (data.loading != 1) tipsFun.toast.error(res.data.message||Config.ERRORMSG);
				}
			},
			fail: (err) => {
				// 上传失败
				console.log("**************************")
				console.log("接口错误，接口："+apiName)
				console.log("接口错误，参数："+JSON.stringify(data))
				console.log("接口错误，返回值："+JSON.stringify(err))
				console.log("**************************")
				tipsFun.toast.close();
				errorCallback && errorCallback(err);
				if (data.loading != 1) tipsFun.toast.error('上载文件失败')
			},
			complete: () => {
				// 成功、失败都执行

			}
		})
	},
	/**
	 * 单文件上传文件
	 * apiName 接口地址
	 * files 需要上传的文件，arrr类型
	 * data 请求数据
	 * method 请求方式
	 * successCallback 请求成功回调方法
	 * errorCallback 请求失败回调方法
	 */
	UploadFileFromServer(apiName, file, data, successCallback, errorCallback) {
		if (data.loading != 1) tipsFun.toast.loading('正在上传...');
		uni.uploadFile({
			url: Config.SERVERURL + apiName,
			header: {
				'token': Vuex.state.user_token,
				'platform' : Vuex.state.platform,
				'deviceId' : Vuex.state.deviceId,
			},
			filePath: file.filePath,
            name: file.name,
			formData: data,
			success: (res) => {
				if(typeof(res.data) == "string"){
					res.data = JSON.parse(res.data);
				}
				// 上传成功
				tipsFun.toast.close();
				if (res.data.code == Config.SUCCESSCODE) {
					successCallback && successCallback(res.data);
				} else {
					console.log("**************************")
					console.log("失败，接口："+apiName)
					console.log("失败，参数："+JSON.stringify(data))
					console.log("失败，返回值："+JSON.stringify(res))
					console.log("**************************")
					errorCallback && errorCallback(res.data);
					if (data.loading != 1) tipsFun.toast.error(res.data.msg||Config.ERRORMSG);
				}
			},
			fail: (err) => {
				// 上传失败
				console.log("**************************")
				console.log("接口错误，接口："+apiName)
				console.log("接口错误，参数："+JSON.stringify(data))
				console.log("接口错误，返回值："+JSON.stringify(err))
				console.log("**************************")
				tipsFun.toast.close();
				errorCallback && errorCallback(err);
				if (data.loading != 1) tipsFun.toast.error('上载文件失败')
			},
			complete: () => {
				// 成功、失败都执行
	
			}
		})
	},
	//下载文件
	downLoadFile(webUrl, localFilename, sucesscallback, errorcallback) {
		let dtask = plus.downloader.createDownload(webUrl, {
			filename: '_doc/download/abyty/' + localFilename
		}, function(d, status) {
			//下载完成
			if (status == 200) {
				sucesscallback(d.filename);
			} else {
				sucesscallback('/_www/logo.png');
			}
		});
		dtask.start();
	},
	// 压缩图片
	compressImage(src, dst, overwrite, quality, sucessCallback, errorCallBack) {
		plus.zip.compressImage({
			src: src,
			dst: dst,
			overwrite: overwrite,
			quality: quality
		},
		function(e) {
			sucessCallback && sucessCallback(e);
		},
		function(error) {
			errorCallBack && errorCallBack(false);
		});
	}
};
/* 丰收支付*/
let PayForm = {
	 creatPayForm(str) {
		let obj = {
			TransId: str.TransId,
			Plain: str.Plain,
			Signature: str.Signature
		}
		let bodyEle = document.getElementsByTagName('body')[0]
		// let payForm=document.getElementById('payForm')
		// payForm&&bodyEle.removeChild(payForm)
		let formEle = document.createElement('form')
		formEle.action = Config.payUrl
		formEle.method = "post"
		formEle.id = "payForm"
		for (let i in obj) {
			let inputEle = document.createElement('input')
			inputEle.type = "hidden" 
			inputEle.name = i
			inputEle.value = obj[i]
			formEle.appendChild(inputEle)
		}
		bodyEle.appendChild(formEle)
		// formEle.submit()
	},
	  payFormSumit(obj){
		let payForm = document.getElementById('payForm')
		let inputs = payForm.getElementsByTagName('input')
		for (let i = 0, len = inputs.length; i < len; i++) {
			inputs[i].value = obj[inputs[i].name]
		}
		payForm.submit()
	
	}
};

export default {
	defFun,
	apiFun,
	tipsFun,
	mediaFun,
	webViewFun,
	deviceFun,
	localStorage,
	dateFun,
	tabBarFun,
	checkerFun,
	shareFun,
	pushFun,
	PayForm
};